package com.hog.utils;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * HttpClient工具类
 *
 * @author 唐晴
 * @date 2020年09月03日
 * @since JDK 1.8
 */
@Component
@Slf4j
public class HttpClientUtils {

    /**
     * 字符集编码UTF-8
     */
    public static final String CHARSET_UTF8 = "UTF-8";
    /**
     * 内容类型 文本类型
     */
    public static final String CONTENT_TYPE_TEXT = "application/text";
    /**
     * 内容类型 json类型
     */
    public static final String CONTENT_TYPE_JSON = "application/json";
    /**
     * 状态码key
     */
    public static final String KEY_STATUS_CODE = "status";
    /**
     * HTTP实体内容key
     */
    public static final String KEY_ENTITY_CONTENT = "entityContent";
    /**
     * 默认超时时间
     **/
    private static final int DEFUALT_TIMEOUT = 600000;

    /**
     * 发起HTTP POST请求，返回请求结果字符串
     *
     * @param url       请求地址
     * @param paramsMap 请求参数
     * @param charset   字符集编码
     * @return 请求结果
     * @throws ClientProtocolException
     * @throws IOException
     */
    public static String httpPost(String url, Map<String, String> paramsMap, String charset, Map<String, String> headMap)
            throws ClientProtocolException, IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            HttpPost httpPost = new HttpPost(url);
            RequestConfig requestConfig = RequestConfig.custom()
                    .setSocketTimeout(300000).setConnectTimeout(300000).build();
            httpPost.setConfig(requestConfig);
            if (null != headMap && headMap.size() > 0) {
                for (Map.Entry<String, String> entry : headMap.entrySet()) {
                    httpPost.addHeader(entry.getKey(), entry.getValue());
                }
            }
            setPostParams(httpPost, paramsMap);
            CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
            try {
                HttpEntity httpEntity = httpResponse.getEntity();
                return org.apache.http.util.EntityUtils.toString(httpEntity, charset);
            } finally {
                try {
                    httpResponse.close();
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
            }
        } finally {
            try {
                httpClient.close();
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        }
    }

    /**
     * 发起HTTP POST请求，返回请求结果字符串
     *
     * @param url       请求地址
     * @param paramsMap 请求参数
     * @param charset   字符集编码
     * @return 请求结果
     * @throws ClientProtocolException
     * @throws IOException
     */
    public static String httpPost(String url, Map<String, String> paramsMap, String charset)
            throws ClientProtocolException, IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            HttpPost httpPost = new HttpPost(url);
            RequestConfig requestConfig = RequestConfig.custom()
                    .setSocketTimeout(300000).setConnectTimeout(300000).build();
            httpPost.setConfig(requestConfig);
            setPostParams(httpPost, paramsMap);
            CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
            try {
                HttpEntity httpEntity = httpResponse.getEntity();
                return org.apache.http.util.EntityUtils.toString(httpEntity, charset);
            } finally {
                try {
                    httpResponse.close();
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
            }
        } finally {
            try {
                httpClient.close();
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        }
    }

    /**
     * Post方式发送body数据 默认UTF-8,超时时间600000，无请求头参数设定
     *
     * @param url  请求地址
     * @param body 请求体数据
     * @return 请求结果, 异常为空串
     */
    public static String httpPostBody(String url, String body) {
        return httpPostBody(url, body, null, null, null);
    }

    /**
     * Post方式发送body数据
     *
     * @param url         请求地址
     * @param body        请求体数据
     * @param charsetName 编码格式默认UTF-8
     * @param timeout     接口超时时间默认600000
     * @param headMap     请求头参数设定
     * @return 请求结果, 异常为空串
     */
    public static String httpPostBody(String url, String body, String charsetName, Integer timeout, Map<String, String> headMap) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        timeout = null == timeout ? DEFUALT_TIMEOUT : timeout;
        charsetName = null == charsetName || charsetName.isEmpty() ? CHARSET_UTF8 : charsetName;
        Charset charset = Charset.forName(charsetName);
        CloseableHttpResponse httpResponse = null;
        try {
            HttpPost httpPost = new HttpPost(url);
            RequestConfig requestConfig = RequestConfig.custom()
                    .setSocketTimeout(timeout)
                    .setConnectTimeout(timeout)
                    .build();
            httpPost.setConfig(requestConfig);
            if (null != headMap && headMap.size() > 0) {
                for (Map.Entry<String, String> entry : headMap.entrySet()) {
                    httpPost.addHeader(entry.getKey(), entry.getValue());
                }
            }
            httpPost.setEntity(new StringEntity(body, charset));
            httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            return org.apache.http.util.EntityUtils.toString(httpEntity, charset);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            try {
                if (null != httpResponse) {
                    httpResponse.close();
                }
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
            try {
                httpClient.close();
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        }
        return "";
    }

    /**
     * 发起HTTP POST请求，以json提交，返回请求结果字符串
     *
     * @param url     请求地址
     * @param json    请求json
     * @param charset 字符集编码
     * @return 请求结果
     * @throws ClientProtocolException
     * @throws IOException
     */
    public static String httpPost(String url, String json, String charset)
            throws ClientProtocolException, IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            HttpPost httpPost = new HttpPost(url);
            RequestConfig requestConfig = RequestConfig.custom()
                    .setSocketTimeout(300000).setConnectTimeout(300000).build();
            httpPost.setConfig(requestConfig);
            setPostParams(httpPost, json, "application/json;charset=" + CHARSET_UTF8);
            CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
            try {
                HttpEntity httpEntity = httpResponse.getEntity();
                return org.apache.http.util.EntityUtils.toString(httpEntity, charset);
            } finally {
                try {
                    httpResponse.close();
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
            }
        } finally {
            try {
                httpClient.close();
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        }
    }

    /**
     * 发起HTTP POST请求，返回状态码(Integer)和请求结果内容(byte[])<br>
     * 状态码常量见：HttpStatus.SC_OK
     *
     * @param url       请求地址
     * @param paramsMap 请求参数
     * @return 状态码和请求结果内容
     * @throws ClientProtocolException
     * @throws IOException
     */
    public static Map<String, Object> httpPost(String url, Map<String, String> paramsMap)
            throws ClientProtocolException, IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            HttpPost httpPost = new HttpPost(url);
            RequestConfig requestConfig = RequestConfig.custom()
                    .setSocketTimeout(300000).setConnectTimeout(300000).build();
            httpPost.setConfig(requestConfig);
            setPostParams(httpPost, paramsMap);
            Map<String, Object> resultMap = new HashMap<>();
            CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
            try {
                HttpEntity httpEntity = httpResponse.getEntity();
                resultMap.put(KEY_STATUS_CODE, new Integer(httpResponse.getStatusLine().getStatusCode()));
                resultMap.put(KEY_ENTITY_CONTENT, org.apache.http.util.EntityUtils.toByteArray(httpEntity));
                return resultMap;
            } finally {
                try {
                    httpResponse.close();
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
            }
        } finally {
            try {
                httpClient.close();
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        }
    }

    /**
     * 发起HTTP GET请求，返回状态码(Integer)和请求结果内容(byte[])<br>
     * 状态码常量见：HttpStatus.SC_OK
     *
     * @param url 请求地址
     * @return 状态码和请求结果内容
     * @throws ClientProtocolException
     * @throws IOException
     */
    public static Map<String, Object> httpGet(String url) throws IOException {
        return httpGet(url, 300000);
    }

    /**
     * 发起HTTP GET请求，返回状态码(Integer)和请求结果内容(byte[])<br>
     * 状态码常量见：HttpStatus.SC_OK
     *
     * @param url  请求地址
     * @param time 超时时间
     * @return 状态码和请求结果内容
     * @throws ClientProtocolException
     * @throws IOException
     */
    public static Map<String, Object> httpGet(String url, int time) throws IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            HttpGet httpGet = new HttpGet(url);
            RequestConfig requestConfig = RequestConfig.custom()
                    .setSocketTimeout(time).setConnectTimeout(time).build();
            httpGet.setConfig(requestConfig);

            Map<String, Object> resultMap = new HashMap<>();
            CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
            try {
                HttpEntity httpEntity = httpResponse.getEntity();
                resultMap.put(KEY_ENTITY_CONTENT, org.apache.http.util.EntityUtils.toByteArray(httpEntity));
                resultMap.put(KEY_STATUS_CODE, new Integer(httpResponse.getStatusLine().getStatusCode()));
                return resultMap;
            } finally {
                try {
                    httpResponse.close();
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
            }
        } finally {
            try {
                httpClient.close();
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        }
    }


    /**
     * 发起HTTP GET请求，返回状态码(Integer)和请求结果内容(byte[])<br>
     * 状态码常量见：HttpStatus.SC_OK
     *
     * @param url     请求地址
     * @param time    超时时间
     * @param headMap 头信息
     * @return 状态码和请求结果内容
     * @throws ClientProtocolException
     * @throws IOException
     */
    public static Map<String, Object> httpGet(String url, int time, Map<String, String> headMap) throws IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            HttpGet httpGet = new HttpGet(url);
            RequestConfig requestConfig = RequestConfig.custom()
                    .setSocketTimeout(time).setConnectTimeout(time).build();
            httpGet.setConfig(requestConfig);

            if (null != headMap && headMap.size() > 0) {
                for (Map.Entry<String, String> entry : headMap.entrySet()) {
                    httpGet.addHeader(entry.getKey(), entry.getValue());
                }
            }

            Map<String, Object> resultMap = new HashMap<>();
            CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
            try {
                HttpEntity httpEntity = httpResponse.getEntity();
                resultMap.put(KEY_ENTITY_CONTENT, org.apache.http.util.EntityUtils.toByteArray(httpEntity));
                resultMap.put(KEY_STATUS_CODE, new Integer(httpResponse.getStatusLine().getStatusCode()));
                return resultMap;
            } finally {
                try {
                    httpResponse.close();
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
            }
        } finally {
            try {
                httpClient.close();
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        }
    }

    /**
     * Get返回json数据 默认UTF-8,超时时间600000
     *
     * @param url
     * @param charset
     * @param time
     * @param headMap
     * @return
     * @throws IOException
     */
    public static String httpGet(String url, String charset, int time, Map<String, String> headMap) throws IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            HttpGet httpGet = new HttpGet(url);
            RequestConfig requestConfig = RequestConfig.custom()
                    .setSocketTimeout(time).setConnectTimeout(time).build();
            httpGet.setConfig(requestConfig);

            if (null != headMap && headMap.size() > 0) {
                for (Map.Entry<String, String> entry : headMap.entrySet()) {
                    httpGet.addHeader(entry.getKey(), entry.getValue());
                }
            }

            log.info("httpGet: {}", JSONObject.toJSONString(httpGet));
            CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
            try {
                HttpEntity httpEntity = httpResponse.getEntity();
                return org.apache.http.util.EntityUtils.toString(httpEntity, charset);
            } finally {
                try {
                    httpResponse.close();
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
            }
        } finally {
            try {
                httpClient.close();
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        }
    }

    /**
     * 发起HTTP GET请求，返回json
     *
     * @param url     请求地址
     * @param charset 字符集
     * @return json结果
     * @throws ClientProtocolException
     * @throws IOException
     */
    public static String httpGet(String url, String charset) throws IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            HttpGet httpGet = new HttpGet(url);
            RequestConfig requestConfig = RequestConfig.custom()
                    .setSocketTimeout(300000).setConnectTimeout(300000).build();
            httpGet.setConfig(requestConfig);
            CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
            try {
                HttpEntity httpEntity = httpResponse.getEntity();
                return org.apache.http.util.EntityUtils.toString(httpEntity, charset);
            } finally {
                try {
                    httpResponse.close();
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
            }
        } finally {
            try {
                httpClient.close();
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        }
    }

    /**
     * 发起HTTP PUT请求，以json提交，返回请求结果字符串
     *
     * @param url     请求地址
     * @param json    请求json
     * @param charset 字符集编码
     * @return 请求结果
     * @throws ClientProtocolException
     * @throws IOException
     */
    public static String httpPut(String url, String json, String charset)
            throws ClientProtocolException, IOException {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            HttpPut httpPut = new HttpPut(url);
            RequestConfig requestConfig = RequestConfig.custom()
                    .setSocketTimeout(300000).setConnectTimeout(300000).build();
            httpPut.setConfig(requestConfig);
            setPutParams(httpPut, json, "application/json;charset=" + CHARSET_UTF8);
            CloseableHttpResponse httpResponse = httpClient.execute(httpPut);
            try {
                HttpEntity httpEntity = httpResponse.getEntity();
                return org.apache.http.util.EntityUtils.toString(httpEntity, charset);
            } finally {
                try {
                    httpResponse.close();
                } catch (Exception e) {
                    log.error(e.getMessage(), e);
                }
            }
        } finally {
            try {
                httpClient.close();
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        }
    }

    /**
     * 设置POST参数
     *
     * @param httpPost
     * @param paramsMap
     * @throws UnsupportedEncodingException
     * @throws Exception
     */
    private static void setPostParams(HttpPost httpPost, Map<String, String> paramsMap)
            throws UnsupportedEncodingException {
        if (paramsMap == null || paramsMap.isEmpty()) {
            return;
        }
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        Set<String> paramsKeySet = paramsMap.keySet();
        for (String paramKey : paramsKeySet) {
            nvps.add(new BasicNameValuePair(paramKey, paramsMap.get(paramKey)));
        }
        httpPost.setEntity(new UrlEncodedFormEntity(nvps, CHARSET_UTF8));
    }

    /**
     * 设置POST参数，针对StringEntity
     *
     * @param httpPost
     * @param entityStr
     * @param contentType
     * @throws UnsupportedEncodingException
     */
    private static void setPostParams(HttpPost httpPost, String entityStr, String contentType)
            throws UnsupportedEncodingException {
        if (StringUtils.isEmpty(entityStr)) {
            return;
        }
        StringEntity strEntity = new StringEntity(entityStr, CHARSET_UTF8);
        strEntity.setContentEncoding(CHARSET_UTF8);
        strEntity.setContentType(contentType);
        httpPost.setEntity(strEntity);
    }

    /**
     * 设置PUT参数，针对StringEntity
     *
     * @param httpPut
     * @param entityStr
     * @param contentType
     * @throws UnsupportedEncodingException
     */
    private static void setPutParams(HttpEntityEnclosingRequestBase httpPut, String entityStr, String contentType)
            throws UnsupportedEncodingException {
        if (StringUtils.isEmpty(entityStr)) {
            return;
        }
        StringEntity strEntity = new StringEntity(entityStr, CHARSET_UTF8);
        strEntity.setContentEncoding(CHARSET_UTF8);
        strEntity.setContentType(contentType);
        httpPut.setEntity(strEntity);
    }

    public static void main(String[] args) {
        String result = httpPostBody("http://172.17.147.56:9999/cnpd/rest/material/bomConvert"
                , "[\"004.001.0007371\",\"004.002.0000034\"]");
        System.out.println("----------------------");
        System.out.println("result:" + result);
    }
}